package com.javafactroy.kunlong.bip.icp.common.utils;

import org.springframework.cglib.beans.BeanCopier;

import java.util.ArrayList;
import java.util.List;

public class CopyBeanUtils {
    public static <S, D> D CopyBean(Class<S> src, Class<D> dst, S srcInst) throws InstantiationException, IllegalAccessException {
        BeanCopier copier = BeanCopier.create(src, dst, false);
        D dstInst = dst.newInstance();
        copier.copy(srcInst, dstInst, null);
        return dstInst;
    }


    public static <S, D> List<D> CopyBeans(Class<S> src, Class<D> dst, List<S> sList) throws InstantiationException, IllegalAccessException {
        List<D> dList = new ArrayList<>();
        for (S sinst : sList) {
            D dinst = CopyBean(src, dst, sinst);
            dList.add(dinst);
        }
        return dList;
    }

    public static <S, D> D CopyBean(S src, Class<D> dst) throws InstantiationException, IllegalAccessException {
        if(src==null){
            return null;
        }
        BeanCopier copier = BeanCopier.create(src.getClass(), dst, false);

        D dstInt = dst.newInstance();
        copier.copy(src, dstInt, null);

        return dstInt;
    }

    public static <S, D> List<D> CopyBeans(List<S> srcList, Class<D> dst) throws InstantiationException, IllegalAccessException {
        List<D> dstList = new ArrayList<>();
        if (srcList == null) {
            return dstList;
        }

        for (S src : srcList) {
            D d = CopyBean(src, dst);
            dstList.add(d);
        }
        return dstList;
    }
}
